package com.efivestar.idm.api.service.lock.protocol.handler;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.efivestar.idm.api.common.Cons;
import com.efivestar.idm.api.domain.EventDomain;
import com.efivestar.idm.api.domain.Lock2UserDomain;
import com.efivestar.idm.api.repository.EventMapper;
import com.efivestar.idm.api.repository.Lock2UserMapper;
import com.efivestar.idm.api.service.DeviceService;
import com.efivestar.idm.api.service.dto.PowerDto;
import com.efivestar.idm.api.util.ByteUtils;

import io.netty.buffer.ByteBuf;
import tk.mybatis.mapper.entity.Example;

@Service
public class ResetDoorLockProtocolHandler extends AbstractLockProtocolHandler{

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private EventMapper mapper;

    @Autowired
    private Lock2UserMapper lock2UserMapper;

    /**
     * @param buf
     * @param lockId
     * @return
     */
    @Override
    public byte[] handleData(ByteBuf buf, String lockId) {
    	int length = buf.readableBytes();
        //跳过指令码，不读取
        buf.skipBytes(1);
//        读取电量字节
        byte powerBt = buf.readByte();
        PowerDto power = ByteUtils.getPower(powerBt);
//        读取状态
        buf.readBytes(1);
        //读取imei(设备编号)
        // String lockId = String.valueOf(buf.readCharSequence(length - getDataLenthWithoutDeviceId(), Charset.forName("utf-8")));
        //删除智能锁上对应的用户
        lock2UserMapper.deleteByExample(lock2UserWhereCause(lockId));

        //设置设备的电量、防御状态为撤防和更新时间
        deviceService.updatePowerAndDefenseStatus(lockId, power.getPowerPercent(), Cons.DEFENSE_OFF_STATUS);
        //插入事件
        EventDomain event = EventDomain.builder().deviceId(lockId).eventType(Cons.RESET_DOOR_EVENT_TPE).createTime(new Date()).build();
        mapper.insert(event);
        return ByteUtils.hexToBytes("00");
    }

    /**
     * 用户条件查询.
     * @param lockId
     * @return
     */
    private Example lock2UserWhereCause(String lockId) {
        Example example = new Example(Lock2UserDomain.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("lockId", lockId);
        return example;
    }



    @Override
    protected int getDataLenthWithoutDeviceId() {
        return 3;
    }



    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        System.arraycopy(src, begin, bs, 0, count);
        return bs;
    }

    @Override
    public String udpHead(){
        return Cons.UDP_HEAD_EF01;
    }

    @Override
    public String udpCommand(){
        return Cons.UDP_COMMAND_RESET;
    }





}






